//
//  JWMeanie.m
//  wolf3d
//
//  Created by James Weatherley on 10/12/2009.
//  Copyright 2009 James Weatherley. All rights reserved.
//

#import "../koth.h"
#import "../iphone/wolf3dAppDelegate.h"

@implementation JWMeanie

@synthesize master;

+(NSInteger)energy
{
	return 1;
}

-(void)doWork
{	
	JWLandscapeManager* landscapeManager = (JWLandscapeManager*)[[JWManagers sharedManager] managerOfClass:[JWLandscapeManager class]];
	JWLandscape* landscape = (JWLandscape*)[landscapeManager entity];
	
	NSInteger playerX = rint(Player.position.origin[0]);
	NSInteger playerZ = rint(-Player.position.origin[1]);
	
	JWSquare* playerSquare = [landscape getSquareAtX:playerX z:playerZ];
	assert(playerSquare.player);
	
	float angleToPlayer = [self checkPlayer];
	
	if(angleToPlayer < kothSentinelFOV && [self squareVisible:playerSquare]) {
		[(wolf3dAppDelegate*)[UIApplication sharedApplication].delegate emergencyTeleportCanDie:YES];
		[self backToTree];
	} else {
		theta += kothMeanieRotationSpeed;
	}
	if(theta > 360.0f) {
		[self backToTree];
	}
}

-(void)backToTree
{
	JWTreeManager* treeManager = (JWTreeManager*)[[JWManagers sharedManager] managerOfClass:[JWTreeManager class]];
	JWTree* tree = [[[JWTree alloc] initWithSquare:square] autorelease];
	
	// If we don't retain/autorelease, then the next line will dealloc us.
	// This is bad, as we're still in the middle of a method!
	[[self retain] autorelease];
	[[self manager] removeEntity:self];
	square.tree = tree;
	square.sentinel = nil;
	
	[treeManager addEntity:tree];
}

-(void)dealloc
{
	[master meanieFinished];
	[super dealloc];
}

@end
